﻿$.request = function (name) {
    var search = location.search.slice(1);
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] === name) {
            if (unescape(ar[1]) === 'undefined') {
                return "";
            } else {
                return unescape(ar[1]);
            }
        }
    }
    return "";
}

function getModalTitle(title, isback, hideConfirmBtn) {
    var closeBtn = 'close';
    if (isback)
        closeBtn = 'arrow_back';

    var confirmBtn = '<a class="mdui-btn eq-confirm-btn" href="javascript:;"><b><i class="mdui-icon material-icons">check</i> 确认</b></a>';
    if (hideConfirmBtn)
        confirmBtn = '';

    var str = '<header class="mdui-appbar mdui-color-white mdui-text-color-theme mdui-shadow-1">';
    str += '<div class="mdui-toolbar">';
    str += '<span class="eq-closepop-btn mdui-btn mdui-btn-icon "><i class="mdui-icon material-icons">' + closeBtn + '</i></span>';
    str += '<div class=""><b>' + title + '</b></div>';
    str += '<div class="mdui-toolbar-spacer"></div>';
    str += confirmBtn;
    str += '<a href="javascript:;" class="mdui-btn mdui-btn-icon mdui-ripple">';
    str += '<i class="mdui-icon material-icons">more_vert</i>';
    str += '</a>';
    //str += '<ul class="mdui-menu" id="eq-more-vert-action">';
    //str += '<li class="mdui-menu-item"><a href = "javascript:;" class="eq-reload-iframe-btn">刷新</a></li>';
    //str += '</ul>';
    str + '</div>';
    str += '</header>';
    return str;
}

$.modalOpen = function (opts) {
    //top.$.loadingBox(false);
    top.$.loadingLayer(true);
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        isback: false,
        hideConfirmBtn:false,
        shade: 0.3,
        btn: ['<i class="mdui-icon material-icons">check</i> 确认', '<i class="mdui-icon material-icons">close</i> 关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: null
    };
    var options = $.extend(defaults, opts);
 
    var _width = $(window).width() > parseInt(options.width.replace('px', '')) ? options.width : $(window).width() + 'px';
    var _height = $(window).height() > parseInt(options.height.replace('px', '')) ? options.height : $(window).height() + 'px';

    
    top.layer.open({
        id: options.id,
        type: 2,
        icon: -1,
        anim: 2,
        isOutAnim:false,
        shade: options.shade,
        //title: '<i class="mdui-icon material-icons">arrow_back</i> ' + options.title,
        title: getModalTitle(options.title, options.isback, options.hideConfirmBtn),
        closeBtn:0,
        fix: false,
        area: [_width, _height],
        content: options.url,
        btn: options.btn,
        btnclass: options.btnclass,
        move:false,
        yes: function (index) {
            var val = "layui-layer-iframe" + index;
            options.callBack(val);
        }, cancel: function () {
            return true;
        },
        success: function (layero, index) {
            
            top.$('.layui-layer-btn0').addClass('mdui-btn mdui-text-color-theme mdui-ripple');
            top.$('.layui-layer-btn1').addClass('mdui-btn mdui-text-color-theme-accent mdui-ripple');
            top.$('.layui-layer-title').addClass('mdui-color-theme');
            if (!options.hideConfirmBtn) {
                top.$(layero).find('.eq-confirm-btn').bind('click', function () {
                    top.$(layero).find('.layui-layer-btn0').trigger('click');
                });
            }
            top.$(layero).find('.eq-closepop-btn').bind('click',function () {
                top.layer.close(index);
            });


            layero.find('.eq-reload-iframe-btn').bind('click', function () {
                var body = top.layer.getChildFrame('body', index);
                var iframeWin = top.window[layero.find('iframe')[0]['name']];
                iframeWin.location.reload();
            });
        }
    });
};


$.modalOpen2 = function (opts) {
    top.$.loadingLayer(true);
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        isback: false,
        hideConfirmBtn: false,
        shade: 0.3,
        btn: ['<i class="mdui-icon material-icons">check</i> 确认', '<i class="mdui-icon material-icons">close</i> 关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: null,
        success:null
    };
    var options = $.extend(defaults, opts);

    var _width = $(window).width() > parseInt(options.width.replace('px', '')) ? options.width : $(window).width() + 'px';
    var _height = $(window).height() > parseInt(options.height.replace('px', '')) ? options.height : $(window).height() + 'px';


    top.layer.open({
        id: options.id,
        type: 2,
        icon: -1,
        anim: 2,
        isOutAnim: false,
        shade: options.shade,
        //title: '<i class="mdui-icon material-icons">arrow_back</i> ' + options.title,
        title: getModalTitle(options.title, options.isback, options.hideConfirmBtn),
        closeBtn: 0,
        fix: false,
        area: [_width, _height],
        content: options.url,
        btn: options.btn,
        btnclass: options.btnclass,
        move: false,
        yes: function (layero,index) {
            
            options.callBack(index, layero);
        }, cancel: function () {
            return true;
        },
        success: function (layero, index) {
            if (options.success !== null) {
                options.success(layero, index);
            }

            top.$('.layui-layer-btn0').addClass('mdui-btn mdui-color-theme mdui-ripple');
            top.$('.layui-layer-btn1').addClass('mdui-btn mdui-color-theme-accent mdui-ripple');
            top.$('.layui-layer-title').addClass('mdui-color-theme');
            //layero.find('.layui-layer-btn').css('display', 'none');
            if (!options.hideConfirmBtn) {
                top.$(layero).find('.eq-confirm-btn').bind('click', function () {
                    top.$(layero).find('.layui-layer-btn0').trigger('click');
                });
            }
            top.$(layero).find('.eq-closepop-btn').bind('click', function () {
                top.layer.close(index);
            });

            layero.find('.eq-reload-iframe-btn').bind('click', function () {
                var body = top.layer.getChildFrame('body', index);
                var iframeWin = top.window[layero.find('iframe')[0]['name']];

                iframeWin.location.reload();
            });
        }
    });
};

$.fn.formSerialize = function (formdate) {

    var element = $(this);

    if (typeof formdate !== 'undefined') {
        for (var key in formdate) {

            var $id = element.find('#' + key);
            var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            if ($id.hasClass("select2-hidden-accessible")) {
                type = "select";
            }
            if (typeof ($id.attr('multiple')) !== "undefined") {
                type = "select2";
                //alert(key);
            }

            if ($id.hasClass('input-wdatepicker')) {
                type = "wddate";
            }

            switch (type) {
                case "checkbox":
                    if (value === "true") {
                        $id.attr("checked", 'checked');
                    } else {
                        $id.removeAttr("checked");
                    }
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    break;

                case "select2":
                    if (value.indexOf(',') < 0) {
                        $id.val(value).trigger("change");
                    }
                    else {
                        var vals = value.split(',');

                        $id.val(vals).trigger('change');

                    }
                    break;

                case "wddate":
                    if (value.length > 0) {
                        $id.val(value.split(' ')[0]);
                    }
                    break;

                default:
                    $id.val(value);
                    break;
            }
        };
        return false;
    }
    var postdata = {};

    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);

        var id = $this.attr('id');
        var type = $this.attr('type');
        if ($this.hasClass("eq-editor")) {
            type = "textarea1";
        }
        if (typeof ($this.attr('multiple')) !== "undefined") {
            type = "select2";
        }


        switch (type) {
            case "checkbox":
                postdata[id] = $this.is(":checked");
                break;

            case "radio":
                var name = $this.attr('name');
                postdata[name] = $("input[name='" + name + "']:checked").val();
                break;

            case "select2":

                postdata[id] = "";
                if ($this.val() === null) {
                    postdata[id] = null;
                }
                else {
                    var val = $this.val();
                    for (var i = 0; i < val.length; i++) {
                        postdata[id] += ',' + val[i];
                    }
                    postdata[id] = postdata[id].substr(1);
                }

                break;
            
            
            default:
                var value = $this.val() === "" ? "&nbsp;" : $this.val();
                if (value !== null) {
                    value = value.replace(/&nbsp;/g, '');
                }
                postdata[id] = value;
                break;
        }
    });
    if ($('[name=__RequestVerificationToken]').length > 0) {
        postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }

    return postdata;
};

$.modalMessage = function (text) {
    top.layer.msg('<div class="mdui-text-color-theme-accent"><i class="mdui-icon material-icons">warning</i> ' + text + "</div>");
};

$.snackbar = function (message, icon) {
    mdui.snackbar(message,
        {
            position: 'bottom'
        }
    );
};

$.modalClose = function () {
    
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    //alert(index);
    parent.layer.close(index);
};

$.currentWindow = function () {
    var iframeId = top.$("#eq-manage-tabcontent iframe:visible").attr("id");
    return top.frames[iframeId];
};

$.modalConfirm = function (content, callBack) {
    top.layer.confirm(content, {
        //icon: "fa-list",
        title: '<div class="mdui-p-l-1 mdui-valign"><i class="mdui-icon material-icons">error_outline</i><span class="">系统提示</span></div>',
        btn: ['确认', '取消'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        success: function (layero, index) {
            layero.find('.layui-layer-btn0').addClass('mdui-btn mdui-color-theme');
            layero.find('.layui-layer-btn1').addClass('mdui-btn ');
            
        }
    }, function (index) {
        top.layer.close(index);
        callBack(true);
    }, function () {
        callBack(false);
    });
};

$.modalAlert = function (content, type) {
    var icon = "";
    if (type === 'success') {
        icon = '<i class="  mdui-text-color-theme mdui-icon material-icons">check</i>';
    }
    if (type === 'error') {
        icon = '<i class="  mdui-text-color-red mdui-icon material-icons">error_outline</i>';
    }
    if (type === 'warning') {
        icon = '<i class="  mdui-text-color-orange mdui-icon material-icons">warning</i>';
    }
    top.layer.alert(content, {
        //icon: icon,
        title: "<div class='mdui-p-l-1 mdui-valign'>"+icon+" &nbsp;&nbsp;<span>系统提示<span></div>",
        btn: ['确认'],
        btnclass: ['btn btn-primary'],
        success: function (layero, index) {
            layero.find('.layui-layer-btn0').addClass('mdui-btn mdui-color-theme');
            //top.$('.layui-layer-title').addClass('mdui-color-theme');
        }
    });
};

$.submitForm = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true
    };
    options = $.extend(defaults, options);
    top.$.loadingLayer(true);
    window.setTimeout(function () {
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }

        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                top.$.loadingLayer(false);
                if (data.state === "success") {
                    options.success(data);
                    //top.$.snackbar('<i class="mdui-icon material-icons mdui-text-color-green">check</i> ' + data.message, data.state);
                    top.$.successLayer();
                    if (options.close === true) {
                        $.modalClose();
                    }
                } else {
                    //alert(data.message);
                    $.modalAlert(data.message, data.state);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                top.$.loadingLayer(false);
                $.modalAlert(errorThrown, "error");
            },
            
            complete: function () {
                top.$.loadingLayer(false);
            }
        });
    }, 500);
};

$.deleteForm = function (opts) {
    var defaults = {
        prompt: "您确定要删除该项数据吗？",
        url: "",
        param: [],
        loading: "正在删除数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, opts);
    if ($('[name=__RequestVerificationToken]').length > 0) {
        options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    $.modalConfirm(options.prompt, function (r) {
        if (r) {
            top.$.loadingLayer(true);
            window.setTimeout(function () {
                $.ajax({
                    url: options.url,
                    data: options.param,
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        top.$.loadingLayer(false);
                        //alert(JSON.stringify(data));
                        if (data.state === "success") {
                            options.success(data);
                            top.$.successLayer();
                            //top.$.snackbar('<i class="mdui-icon material-icons mdui-text-color-green">check</i> ' + data.message, data.state);
                        } else {
                            top.$.errorLayer(data.message, data.state);
                        }
                    }
                    
                });
            }, 500);
        }
    });

};


$.fn.SelectDown = function (opts) {
    var defaults = {
        id: 'TreeCollapse',
        title: '请选择',
        url: "",
        success: null
    };
    var options = $.extend(defaults, opts);
    var $this = $(this);
    $this.bind('click', function () {
        $.modalOpen2({
            id: 'ChooseSelect',
            title: '选择',
            url: options.url,
            width: top.getViewPort().width>600?'60%':'100%',
            height: '100%',
            isback: true,
            hideConfirmBtn: true,
            btn: null,
            success: function (layero, index) {
                
                if (options.success !== null) {
                    options.success(layero, index);
                }
            }
        });
    });


};



$.fn.SelectDown2 = function (opts) {
    var defaults = {
        id:'TreeCollapse',
        title:'请选择',
        url: "",
        success: null
    };
    var options = $.extend(defaults, opts);
    var $this = $(this);
    var scrollHeight = $('body')[0].scrollHeight;
    $this.bind('click', function () {
        layer.open({
            id: options.id,
            type: 2,
            title: '<div class="mdui-m-l-2">' + options.title + '</div>',
            content: options.url,
            shade: 0,
            anim: 0,
            shadeClose: true,
            area: [$this.outerWidth() + 'px', '400px'],
            move: false,
            fixed: false,
            offset: [$this.offset().top + $this.outerHeight() + 'px', $this.offset().left + 'px'],
            success: function (layero, index) {
                if (options.success !== null) {
                    options.success(layero, index);
                }

                $(window).resize(function () {
                    layero.css('top', $this.offset().top + $this.outerHeight() + 'px');
                    layero.css('left', $this.offset().left + 'px');
                    layero.css('width', $this.width() + 'px');
                });
            }
        });
    });
    
    
};


$.fn.SelectIcon = function (opts) {
    var defaults = {
        targetInput: '',
    };
    var options = $.extend(defaults, opts);
    var $this = $(this);
    $this.bind('click', function () {
        $.modalOpen2({
            id: 'ChooseIcon',
            title: '选择图标',
            url: '/MaterialIcon/Index',
            width: '100%',
            height: '100%',
            isback: true,
            hideConfirmBtn: true,
            btn: null,
            success: function (layero, index) {
                var iw = top.window[layero.find('iframe')[0]['name']];
                iw.$('.icon-code-wrap').click(function () {
                    var val = $(this).attr('data-icon-name');
                    $(options.targetInput).val(val);
                    $this.find('i').html(val);
                    top.layer.close(index);
                });
            }
        });
    });
};



